package com.wn.icloud.auth.controller;

import com.wn.icloud.auth.service.AuthService;
import com.wn.icloud.common.util.user.JwtAuthenticationRequest;
import com.wn.icloud.common.msg.ObjectRestResponse;
import com.wn.icloud.provider.uac.remote.vo.LoginReqVO;
import com.wn.icloud.provider.uac.remote.vo.ResetUserPassWordReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/jwt")
@Slf4j
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    /**
     * 手机号密码登陆
     * @param loginReqVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public ObjectRestResponse createAuthenticationToken(
            @RequestBody LoginReqVO loginReqVO) throws Exception {
        log.info(loginReqVO.getUsername()+" require logging...");
        return authService.login(loginReqVO);
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ObjectRestResponse<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new ObjectRestResponse<>().data(refreshedToken);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public ObjectRestResponse<?> verify(String token) throws Exception {
        authService.validate(token);
        return new ObjectRestResponse<>();
    }


    /**
     *手机号验证码登陆
     * @param loginReqVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "phoneToken", method = RequestMethod.POST)
    public ObjectRestResponse createPhoneAuthenticationToken(
            @RequestBody LoginReqVO loginReqVO) throws Exception {
        log.info(loginReqVO.getUsername()+" require logging...");
        return authService.loginPhone(loginReqVO);
    }

    /**
     * 根据手机号码随机生成16为密码修改密码只能使用一次,同时验证code是否正确
     */
    @RequestMapping(value = "resetPassCode", method = RequestMethod.POST)
    public ObjectRestResponse resetPassCode(@RequestBody ResetUserPassWordReqVO resetUserPassWordReqVO){
        return authService.resetPassCode(resetUserPassWordReqVO);
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "resetPass", method = RequestMethod.POST)
    public ObjectRestResponse resetUserPassWord(@RequestBody ResetUserPassWordReqVO resetUserPassWordReqVO){
        return authService.resetUserPassWord(resetUserPassWordReqVO);
    }

    /**
     * 获取版本信息
     */
    @GetMapping(value = "version")
    public ObjectRestResponse versionInfo(String version){
        return authService.versionInfo(version);
    }


}
